<template>
    <view class="EnumSelect">
        <view @click="show">
            <u-input v-if="!onlyPicker" :value="name" :placeholder="placeholder" style="pointer-events: none" :disabled="disabled" :suffixIcon="disabled ? '' : 'arrow-right'" suffixIconStyle="font-size: 22px;color: #909399" readonly> </u-input>
        </view>
        <u-picker :show="isShow" :columns="columns" @confirm="onConfirm" @cancel="hide" :keyName="label" @close="hide" :closeOnClickOverlay="true" :defaultIndex="defaultIndex"></u-picker>
    </view>
</template>

<script>
export default {
    name: "EnumSelect",
    data() {
        return {
            columns: [],
            defaultIndex: [0],
            isShow: false,
        };
    },

    props: {
        //双向绑定的的id和name
        id: [Number, Array, String],
        name: [String, Array],
        obj: null,

        //表名
        enums: {
            type: Object,
        },

        //下拉列表显示名称
        label: {
            type: String,
            default: "text",
        },

        //下拉列表选择的值
        value: {
            type: String,
            default: "value",
        },

        //提示信息
        placeholder: {
            type: String,
            default: "请选择",
        },

        //是否只显示Picker，如果为true，则需要通过父组件其它事件来触发显示或隐藏
        onlyPicker: {
            type: Boolean,
            default: false,
        },
        disabled: {
            type: Boolean,
            default: false,
        },
    },
    created() {
        this.columns = [this.enums.ToArray()];
    },
    watch: {},
    methods: {
        //显示选择框
        show(_idx = 0) {
            if (this.disabled) return;
            this.isShow = true;
            this.$emit("onShow");
        },

        //隐藏选择框
        hide() {
            this.isShow = false;
            this.$emit("onClose");
        },

        onConfirm(obj) {
            console.log(obj);
            if (obj == null || obj.value == null) {
                this.$emit("update:id", null);
                this.$emit("update:name", null);
                this.$emit("update:obj", null);
            } else {
                let selectObj = obj.value[0];
                console.log(selectObj);
                this.$emit("update:id", selectObj[this.value]);
                this.$emit("update:name", selectObj[this.label]);
                this.$emit("update:obj", selectObj);
            }

            this.hide();

            //向外抛出一个事件，可在父组件中用来处理change事件
            this.$emit("onChange");

            console.log(this.id);
            console.log(this.name);
            console.log(this.obj);
        },
    },
};
</script>

<style>
.EnumSelect {
    width: 100%;
}
</style>
